<template>
  <el-form label-width="100px" :model="skuInfo" ref="skuformRef">
    <el-form-item label="SPU名称">
      <span>{{ spuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input v-model="skuInfo.price" type="number"></el-input>
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input v-model="skuInfo.weight" type="number"></el-input>
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="c1, index in attrList" :key="c1.id" :md="12" :sm="12" :xs="24" :lg="8">


          <el-form-item :label="c1.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" placeHolder="请选择">

              <el-option v-for="attrValue in c1.attrValueList" :key="attrValue.id" :label="attrValue.valueName"
                :value="`${c1.id}:${c1.attrName}:${attrValue.id}:${attrValue.valueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">




      <el-form-item :label="saleAttr.saleAttrName" v-for="saleAttr, index in spuSaleAttrList" :key="saleAttr.id">
        <el-select v-model="skuInfo.skuSaleAttrValueList[index]" placeHolder="请选择">

          <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id"
            :label="saleAttrValue.saleAttrValueName"
            :value="saleAttr.id + ':' + saleAttr.saleAttrName + ':' + saleAttrValue.id + ':' + saleAttrValue.saleAttrValueName" />
        </el-select>
      </el-form-item>

    </el-form-item>
    <el-form-item label="图片列表"   >
      <el-table border :data="spuImageList"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片" align="center">

          <template v-slot="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.imgUrl" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="primary" v-if="row.isDefault == '0'" @click="setDefault(row)">设为默认项</el-button>
            <el-button type="success" v-else>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm(skuformRef)">保存</el-button>
      <el-button @click="emits('ShowStatus', ShowStatus.SPU_LIST)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm'
}
</script>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { ref, reactive, onMounted } from "vue"
import { reqSkulist, reqAddsku, } from "@/api/product/sku"
import { reqGetAttrListData } from "@/api/product/Attr"
import { reqspuImageData, reqgetAttrData, } from "@/api/product/spu"
import { useCategorySelectorStore } from "@/stores/CategoryList"
import { ShowStatus } from "./type"
const Sealctor = useCategorySelectorStore()
const props = defineProps(["spuInfo"])
const emits = defineEmits(['ShowStatus']);
const skuformRef = ref<FormInstance>()
//存储数据的
const spuImageList = ref([]);
//销售属性
const spuSaleAttrList = ref([]);
const attrList = ref([]);
//定义一个skuInfo的对象
const skuInfo = reactive({
  spuId: 0,
  category3Id: 0,
  //spu名称
  skuName: '',
  //价格
  price: 0,
  //重量
  weight: 0,
  //描述
  skuDesc: '',
  //默人图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
})



//1页面以挂载就要发送请求了
onMounted(async () => {

  const [reqSpuImage, reqSale, reqAttr] = await Promise.all([reqspuImageData(props.spuInfo.id), reqgetAttrData(props.spuInfo.id), reqGetAttrListData({

    category1Id: Sealctor.category1Id as number,
    category2Id: Sealctor.category2Id as number,
    category3Id: Sealctor.category3Id as number


  })])
  spuImageList.value = reqSpuImage.map(item => {
    return {
      ...item,
      isDefault: '0'
    }
  });
  spuSaleAttrList.value = reqSale;
  attrList.value = reqAttr;
})

const setDefault = (row) => {
  spuImageList.value.map(item => {
    item.isDefault = '0'
  })
  row.isDefault = '1'

}

// 2. 添加skuInfo
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
  
      let flag = skuInfo.skuImageList.every(item => item.isDefault == '0');
      console.log(flag)
      if (flag) {
        ElMessage.warning('请在选择的图片中设置一个默认图片');
        return;
      }

      skuInfo.spuId = props.spuInfo.id;
      skuInfo.category3Id = Sealctor.category3Id as number;

     
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
        // console.log('cc',item)
        const [attrId, attrName, valueId, valueName] = item.split(':');
        return {
          attrId,
          attrName,
          valueId,
          valueName
        };
      });

      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':');
        return {
          saleAttrId,
          saleAttrName,
          saleAttrValueId,
          saleAttrValueName
        };
      });


      // 4.4 发送请求 实现添加
      await reqAddsku(skuInfo);

      // 4.5 提示
      ElMessage.success('添加skuInfo成功了...');

      emits('ShowStatus', ShowStatus.SPU_LIST)
    } else {
      console.log('error submit!', fields);
    }
  });
};
//3
const handleSelectionChange = (val) => {
  skuInfo.skuImageList = val;

}
</script>

<style>

</style>